package com.wl.wuliu.service.impl;

import cn.hutool.core.util.ClassUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wl.wuliu.entity.Customer;
import com.wl.wuliu.mapper.CustomerMapper;
import com.wl.wuliu.result.AjaxResult;
import com.wl.wuliu.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @Author: gutaozhen
 * @Date: 2024/5/15
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public AjaxResult saveCustomer(Customer customer) {

        customer.preInsert();
        save(customer);

        return AjaxResult.success();
    }

    @Override
    public void exportCustomer(HttpServletResponse response) throws IOException {
        List<Customer> customers = customerMapper.selectList(new QueryWrapper<>());

        // 填充数据，导出
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).excelType(ExcelTypeEnum.XLS)
                .withTemplate(ClassUtil.getClassPath() + "/template/customer-export.xls").build()
        ) {
            WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(customers, fillConfig, writeSheet);

            excelWriter.finish();
        }
    }
}
